package cn.pzaily.fealetter.service.impl;

import cn.pzaily.crab.tools.core.utils.ObjectUtils;
import cn.pzaily.fealetter.entity.BlackListEntity;
import cn.pzaily.fealetter.enumeration.RedisPropertiesKey;
import cn.pzaily.fealetter.mapper.BlackListMapper;
import cn.pzaily.fealetter.service.BlackListService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @PackageName: cn.pzaily.fealetter.service.impl
 * @Description:
 * @Author: Pang
 * @Date: 2021-11-21 19:23
 */
@Service
public class BlackListServiceImpl extends
        ServiceImpl<BlackListMapper, BlackListEntity> implements BlackListService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<String> findBlackListByType(String type) {

        ValueOperations<String, List<String>> ops = redisTemplate.opsForValue();
        List<String> phones = ops.get(RedisPropertiesKey.BLACK_MOBILE + type);
        if (CollectionUtils.isEmpty(phones)) {
            List<BlackListEntity> blackListEntities =
                    baseMapper.selectList(new LambdaQueryWrapper<BlackListEntity>().eq(BlackListEntity::getType, type));
            phones = blackListEntities.stream().map(item -> item.getContent()).collect(Collectors.toList());
            if (ObjectUtils.isNull(phones)) {
                phones = Collections.emptyList();
            }
            ops.set(RedisPropertiesKey.BLACK_MOBILE + type, phones, RedisPropertiesKey.TIME, RedisPropertiesKey.TIME_UNIT);
        }
        return phones;
    }
}
